/**
 * Created by Kiva on 17/1/9.
 */
(function ($maintenanceInspectionSheet) {
    //var hostUrl="http://127.0.0.1:8080/clinic-web";
    var hostUrl = Param["host_url"];
    var $inspectionContainer = $maintenanceInspectionSheet.find(".billing-tree:first").parent().children();
    var $examineClassify = $inspectionContainer.eq(0);
    var $examineSetMeal = $inspectionContainer.eq(1);
    var $examineDetail = $inspectionContainer.eq(2);
    var $listDiv = $maintenanceInspectionSheet.siblings(".absolute-table:first");

    showDepartments({"position": "depId", "field": "depId", "isIncludeNull": true, "ismultiple": true});

    function showDepartments(element) {
        ajaxNormalPost("/pub/departments/load_departments", {}, function (data) {
            if (data.length == 0) {
                return;
            }
            if (!element.position) {
                return;   //未标识下拉显示位置
            }
            var defClass = "form-control";
            var multipleHtml = "";
            if (element.ismultiple) {
                // multipleHtml = "multiple=\"multiple\"";
                selectHtml = "<select class=\"" + defClass + "\" name= \"" + element.field + "\" id=\"" + element.field + "\"" + multipleHtml + ">";

                if (element.isIncludeNull) {
                    selectHtml += "<option selected=\"selected\" value=''>-请选择-</option>";
                }
                $(data).each(function (index, Departments) {
                    //createSelect(projectClass, element);//下拉框
                    selectHtml += "<option value=\"" + Departments.id + "\">" + Departments.depName + "</option>";
                })
                selectHtml += "</select>";
                $("#" + element.position).append(selectHtml);
            }
        })
    }

    $listDiv.on("click", function () {
        return false;
    });

    $(document).ready(function () {
        $examineDetail.children("header").find("button:first").on("click", function () {
            var $trs = $examineDetail.find("tBody").find("tr").find("input").parent().parent();
            var _$tBody = $trs.parent();
            detailSubmit($trs, _$tBody.attr("binId"), _$tBody.attr("hospitalId"));
        });
        $(document).on("click", function () {
            $listDiv.fadeOut();
        });
        $examineClassify.children("header").find("i.icon-xinzeng").click(function () {
            addClassify();
        });

        $examineClassify.children("header").find("i.icon-xiugai").click(function () {
            editClassify();
        });
        $examineClassify.children("header").find("i.icon-zhuxiao").click(function () {
            deleteClassify();
        });

        $examineSetMeal.children("header").find("i.icon-xinzeng").click(function () {
            addInfo();
        });

        $examineSetMeal.children("header").find("i.icon-xiugai").click(function () {
            $examineSetMeal.find("tr.selected").length > 0 ? editInfo() : alert("请选择要修改的套餐数据");
        });

        $examineSetMeal.children("header").find("i.icon-zhuxiao").click(function () {
            $examineSetMeal.find("tr.selected").length > 0 ? deleteInfo() : alert("请选择要删除的套餐数据");
        });
    });

    function detailSubmit($trs, binId, hospitalId) {
        if ($trs.length == 0) return;
        var arr = [];
        $.each($trs, function () {
            var $tr = $(this);
            var $tds = $tr.find("td");
            var binNumber = $tds.eq(1).find("input:first").val();
            var itemId = $tr.attr("itemId");
            var detail = {itemId: itemId, binNumber: binNumber};
            arr.push(detail);
        });
        var billDetailList = {billDetailList: arr};
        log4j.info(arr);
        $.ajax({
            url: hostUrl + "/cli/bill_detail/create_bill_detail?binId=" + binId + "&hospitalId=" + hospitalId,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "post",
            data: JSON.stringify(billDetailList),
            success: function (data) {
                log4j.info(data);
                setDetailChange(binId, hospitalId);
            }
        })
    }


    //树菜单伸缩是方法
    function menuExpended($li) {
        var $a = $li.children("a:first");
        var $i = $a.find("span.icon");
        if (!$a.hasClass("menuItem")) {
            var $aUl = $a.siblings("ul");
            $aUl.attr("menu-expanded") == "false" ? ($aUl.slideDown(), $aUl.attr("menu-expanded", "true"), arrowRotate($i)) : ($aUl.slideUp(), $aUl.attr("menu-expanded", "false"), arrowRotate($i));
        }
        var $liSiblings = $li.siblings("li");
        var $liCUl = $li.children("ul");
        if ($liCUl.attr("menu-expanded")) {
            $liSiblings.each(function () {
                var $this = $(this);
                var $a = $this.children("a");
                var $ul = $this.children("ul");
                var $i = $a.find("span.icon");
                if ($ul.attr("menu-expanded") == "true") {
                    $ul.slideUp();
                    $ul.attr("menu-expanded", "false");
                    arrowRotate($i);
                }
            })
        }
    }

    //树标签旋转的方法
    function arrowRotate($i) {
        $i.hasClass("arrow-rotate") ? ($i.addClass("arrow-rotate-recover"), $i.removeClass("arrow-rotate")) : ($i.addClass("arrow-rotate"), $i.removeClass("arrow-rotate-recover"));
    }

    //树点击的方法
    function menuClick($li) {
        var $a = $li.find("a:first");
        if ($a.hasClass("menuItem")) {
            var flag = $a.hasClass("menuFocus");
            $(".billing-tree").find(".menuItem").removeClass("menuFocus");
            flag ? $a.removeClass("menuFocus") : $a.addClass("menuFocus");
        }
    }


    //点击分类加载套餐的方法，需要传入a标签的jQuery对象，ajax获得的套餐的数据，检查还是检验的ID，要过滤的blsId和blsType,后两个参数可以省略
    function classifyInsert($examineA, data, blsId, filterBlsId, filterBlsType) {
        if (filterBlsType == undefined) filterBlsType = -2;
        if (filterBlsId == undefined) filterBlsId = -2;
        var myData = JSON.parse(JSON.stringify(data.data));
        var $examineLi = $examineA.parent();
        for (var i = 0; i < myData.length; i++) {
            if (myData[i].blsType == filterBlsType || myData[i].blsId == filterBlsId) {
                myData.splice(i, 1);
                i--;
            }
        }
        var html = '<ul class="nav nav-second d-n" menu-expanded="false">';
        for (var j = 0; j < myData.length; j++) {
            if (myData[j].blsId == blsId) {
                html += '<li><a href="javascript:void(0)" data-id="' + myData[j].id + '"> <span class="nav-label">' + myData[j].blsName + '</span> <span class="icon icon-xiangyou"></span></a></li>';
            }
        }
        html += '</ul>';
        $examineLi.append(html);
        $.each($examineA.siblings("ul").children("li"), function () {
            var $li = $(this);
            var $a = $li.children("a");
            var _blsId = $a.attr("data-id");
            html = '<ul class="nav nav-third d-n" menu-expanded="false">';
            $.each(myData, function (i, value) {
                if (value.blsId == _blsId) {
                    html += '<li><a href="javascript:void(0)" class="menuItem" data-id="' + value.id + '"> <span class="nav-label">' + value.blsName + '</span></a></li>';
                }
            });
            html += '</ul>';
            $li.append(html);
        });
        $.each($examineLi.find("a"), function () {
            var $a = $(this);
            var $ul = $a.siblings("ul");
            if ($ul.children().length == 0) {
                $a.addClass("menuItem");
                $ul.remove();
                var $spans = $a.children("span");
                $spans.each(function () {
                    if ($(this).hasClass("icon")) $(this).remove();
                });
            }
        });
        $examineClassify.find("li").on("click", function () {
            var $li = $(this);
            var $a = $li.children("a.menuItem");
            menuExpended($li);
            menuClick($(this));
            setMealChange($examineSetMeal, $a);
            return false;
        });
    }


    loadClassify();

    function loadClassify() {
        $.ajax({
            url: hostUrl + "/cli/bill_classify/page_wrapper_jiancha?" + new Date(),
            dataType: "json",
            type: "post",
            success: function (data) {
                var $li = $maintenanceInspectionSheet.find(".nav:first").find("li:first");
                var $examineA = $li.children("a:first");
                $examineA.find("span").removeClass("arrow-rotate").removeClass('arrow-rotate-recover');
                $examineA.siblings().remove();
                $examineA.parent().off("click");
                classifyInsert($examineA, data, -1, 0, 1);
                $li.click();
            },
            error: function () {
                alert("查询错误");
            }
        });
    }

    //页面加载时通过ajax异步加载分类的数据


    //根据分类的点击，套餐显示不同的数据的方法
    function setMealChange($examineSetMeal, $a) {
        if ($a.length == 0) return;
        var id = $a.attr("data-id");
        var $tBody = $examineSetMeal.find("tbody");
        $tBody.html("");
        $.ajax({
            url: hostUrl + "/cli/bill_info/page_wrapper_jiancha?id=" + id,
            async: true,
            dataType: "json",
            type: "post",
            success: function (data) {
                var html = "";
                $.each(data.data, function () {
                    html += '<tr data-id="' + this.id + '" data-hospital-id="' + this.hospitalId + '"><td colspan="6">' + this.binNormCode + '</td><td colspan="4">' + this.binName + '</td><td colspan="4">' + this.depIdWrapper + '</td></tr>';
                });
                $tBody.append(html);
                var $trs = $tBody.find("tr");
                $trs.on("click", function () {
                    var $tr = $(this);
                    var dataId = $tr.attr("data-id");
                    var hospitalId = $tr.attr("data-hospital-id");
                    $tr.addClass("selected");
                    $tr.siblings().removeClass("selected");
                    setDetailChange(dataId, hospitalId);
                });
                $tBody.attr("data-id", id);
            },
            error: function () {
                alert("查询错误！！！");
            }
        });
    }

    //根据套餐加载套餐明细的方法
    function setDetailChange(dataId, hospitalId) {
        $.ajax({
            url: hostUrl + "/cli/bill_detail/page_wrapper_detail?id=" + dataId,
            dataType: "json",
            type: "post",
            success: function (data) {
                log4j.info(data);
                var html = "";
                $.each(data.data, function (i, value) {
                    html += '<tr itemId="' + value.itemId + '" data-id="' + value.id + '"><td colspan="4">' + value.itemName + '</td><td colspan="2">' + value.binNumber + '<td colspan="2">' + value.itemUnit + '</td><td colspan="4">' + value.itemPrice + '</td><td colspan="4"><i class="icon icon-del"></i></td></tr>'
                });
                html += '<tr><td colspan="4"></td><td colspan="2"></td><td colspan="2"></td><td colspan="4"></td><td colspan="4"></td></tr>';
                var $tBody = $examineDetail.find("tBody:first");
                $tBody.html("").append(html);
                inputChange($tBody.find("tr:last"));
                $tBody.attr("binId", dataId).attr("hospitalId", hospitalId);
                $.each($tBody.children("tr"), function () {
                    deleteDetailTr($(this));
                });
            },
            error: function () {
                alert("加载套餐明细失败！");
            }
        });
    }

    //让input和td内的内容相互转换的方法
    function inputChange($tr) {
        var $tds = $tr.find("td");
        $tds.eq(0).on("click", function () {
            var $td = $(this);
            $td.click(function () {
                return false
            });
            addRemoveInput($td, "text");
        });

        function addRemoveInput($td, type) {
            var text;
            text = $td.find("input").length == 0 ? $td.text() : $td.find("input").val();
            $td.html("").append("<input type='" + type + "'>");
            var $input = $td.find("input");
            $input.val(text);
            $input.click(function () {
                return false;
            });
            $input.focus(function () {
                ifGetDetailList($input);
            });

            $input.keydown(function (e) {
                if (e.keyCode == 13) {
                    $input.blur();
                }
            });
            $input.blur(function () {
                var val = $input.val();
                $td.append(val);
                $input.remove();
            });
            $input.on("input propertychange", function () {
                ifGetDetailList($input);
            });

            function ifGetDetailList($input) {
                if ($input.val() != "") {
                    getDetailList($td, 1, 10);
                }
            }

            $input.focus();
        }
    }

    //根据input中输入的字母得到明细的数据
    function getDetailList($td, pageNum, pageSize) {
        var search_chinaSpell = $td.text() || $td.find("input:first").val();
        $.ajax({
            url: hostUrl + "/pub/items/select_spell_stroke_page?search_chinaSpell=" + search_chinaSpell + "&pageNum=" + pageNum + "&pageSize=" + pageSize,
            dataType: "json",
            type: "post",
            async: false,
            success: function (data) {
                var pageTotal = Math.ceil(data.total / pageSize);
                //log4j.info(pageTotal);
                var top = $td.offset().top;
                var left = $td.offset().left;
                //log4j.info(top+"---"+left);
                var width = $td.parents("table").css("width");
                $listDiv.css({"top": top, "left": left, "width": width});
                var bottom = $(document).outerHeight(true) - top - $listDiv.outerHeight(true);
                if (bottom < 10) {
                    top = top - $listDiv.outerHeight(true);
                    $listDiv.css({"top": top, "left": left, "width": width});
                }
                $listDiv.slideDown();
                var $tBody = $listDiv.children("table:first").find("tBody");
                var $page = $listDiv.children("div.page:first");
                var bodyHtml = "";
                $.each(data.rows, function (i, value) {
                    bodyHtml += '<tr itemId="' + value.id + '"><td colspan="6">' + value.itemName + '</td><td colspan="2">' + value.itemUnit + '</td><td colspan="4">' + value.itemPrice + '</td></tr>'
                });
                $tBody.html("").append(bodyHtml);
                $tBody.find("tr").on("click", function () {
                    var $tr = $(this);
                    var $tds = $tr.find("td");
                    var itemId = $tr.attr("itemId");
                    var $detailTBody = $examineDetail.find("tBody:first");
                    var initHtml = '<tr itemId="' + itemId + '"><td colspan="4">' + $tds.eq(0).text() + '</td><td colspan="2"><input type="text" value="0"><td colspan="2">' + $tds.eq(1).text() + '</td><td colspan="4">' + $tds.eq(2).text() + '</td><td colspan="4"><i class="icon icon-del"></i></td></tr>';
                    var $inputTr = $detailTBody.children("tr:last");
                    $inputTr.find("td:first").text("");
                    $inputTr.before(initHtml);
                    $listDiv.fadeOut();
                    deleteDetailTr($inputTr.prev());
                });
                addPaging($td, $page, pageNum, pageTotal);
            },
            error: function () {
                alert("查询错误");
            }
        })
    }

    function deleteDetailTr($tr) {
        var $del = $tr.find("i.icon-del");
        $del.on("click", function () {
            if ($tr.find("input").length > 0) {
                $tr.remove();
            } else {
                var $deleteModal = $("#delete-modal");
                var $submit = $deleteModal.find(".modal-footer").find("button:first");
                var dataId = $tr.attr("data-id");
                var $tBody = $examineDetail.find("tBody");
                var binId = $tBody.attr("binId");
                var hospitalId = $tBody.attr("hospitalId");
                $submit.off("click");
                submitForm(dataId);

                function submitForm(dataId) {
                    $deleteModal.modal("show");
                    $submit.on("click", function () {
                        $.ajax({
                            url: hostUrl + "/cli/bill_detail/delete_by_primary_key?id=" + dataId,
                            dataType: "json",
                            type: "post",
                            async: false,
                            success: function (data) {
                                log4j.info(data);
                                $deleteModal.modal("hide");
                                $tr.remove();
                            },
                            error: function () {

                            }
                        });
                    });
                }
            }
        });
    }

    function addPaging($td, $page, pageNum, pageTotal) {
        var html = "<span>&lt;</span>";
        pageNum = parseInt(pageNum);
        pageTotal = parseInt(pageTotal);
        if (pageTotal <= 5) {
            for (var i = 1; i <= pageTotal; i++) {
                html += '<span>' + i + '</span>';
            }
        } else {
            if (pageNum - 1 <= 1) {
                for (var i = 1; i <= 3; i++) {
                    html += '<span>' + i + '</span>';
                }
                html += '<span>...</span><span>' + pageTotal + '</span>';
            } else if (pageTotal - pageNum <= 2) {
                html += '<span>1</span><span>...</span><span>' + (pageTotal - 3) + '</span><span>' + (pageTotal - 2) + '</span><span>' + (pageTotal - 1) + '</span><span>' + pageTotal + '</span>';
            } else {
                html += '<span>1</span><span>...</span><span>' + (pageNum - 1) + '</span><span>' + pageNum + '</span><span>' + (pageNum + 1) + '</span><span>...</span><span>' + pageTotal + '</span>';

            }
        }
        html += '<span>&gt;</span>';
        $page.html("").append(html);
        $page.children("span").each(function () {
            var $span = $(this);
            var text = $span.text();
            if (text == pageNum) {
                $span.addClass("page-focus");
            } else if (text == "...") {
                $span.addClass("page-n-focus");
            }
        });
        addPagingEven($td, $page, pageNum);
    }

    function addPagingEven($td, $page, pageNum) {
        var $spans = $page.find("span");
        $spans.each(function () {
            var $span = $(this);
            var text = parseInt($span.text());
            if (!isNaN(text)) {
                $span.on("click", function () {
                    if (pageNum != text) {
                        getDetailList($td, text, 10);
                    }
                });
            }
        });
    }

    //点击添加
    function addClassify() {
        var $addClassifyModal = $("#add-classify-modal");
        var $ulThird = $examineClassify.find("ul.nav-third[menu-expanded=true]");
        var $submit = $addClassifyModal.find(".modal-footer").find("button:first");
        var $ulSecond = $examineClassify.find("ul.nav-second");
        $submit.off("click");
        var dataId = $ulThird.length > 0 ? $ulThird.siblings("a").attr("data-id") : $ulSecond.siblings("a").attr("data-id");
        submitForm(dataId);

        function submitForm(dataId) {
            $addClassifyModal.modal("show");
            $addClassifyModal.find("input[type=text]").val("");
            $addClassifyModal.find("input[name=blsType]").val("0");
            $addClassifyModal.find("input[type=checkbox]").prop("checked", false);
            $addClassifyModal.find("input[name=id]").val(dataId);
            $submit.on("click", function () {
                saveClassify($addClassifyModal, "create");
            });
        }
    }

    function editClassify() {
        var $classifyModal = $("#add-classify-modal");
        var $ulThird = $examineClassify.find("ul.nav-third[menu-expanded=true]");
        var $submit = $classifyModal.find(".modal-footer").find("button:first");
        var $IDInput = $classifyModal.find("input[name=id]");
        $IDInput.val("");
        $submit.off("click");
        if ($ulThird.length > 0) {
            var $a = $ulThird.find("a.menuFocus");
            var dataId = $a.length > 0 ? $a.attr("data-id") : $ulThird.siblings("a").attr("data-id");
            submitForm(dataId);
        }

        function submitForm(dataId) {
            $classifyModal.modal("show");
            $.ajax({
                url: hostUrl + "/cli/bill_classify/select_by_primary_key?id=" + dataId,
                dataType: "json",
                type: "post",
                async: false,
                success: function (data) {
                    var $texts = $classifyModal.find("input[type=text]");
                    textVal($texts, data.data);
                    var $checkboxs = $classifyModal.find("input[type=checkbox]");
                    checkboxVal($checkboxs, data.data);
                    $submit.on("click", function () {
                        $IDInput.val(dataId);
                        saveClassify($classifyModal, "update");
                    });
                },
                error: function () {

                }
            });
        }
    }

    function textVal($texts, data) {
        $texts.each(function () {
            var $text = $(this);
            var name = $text.attr("name");
            $text.val(data[name]);
        });
    }

    function checkboxVal($checkboxs, data) {
        $checkboxs.each(function () {
            var $checkbox = $(this);
            var name = $checkbox.attr("name");
            if ($checkbox.attr("value") == data[name]) {
                $checkbox.prop("checked", true);
            }
        });
    }

    //更新或是新增分类的ajax函数
    function saveClassify($addClassifyModal, type) {
        $.ajax({
            url: hostUrl + "/cli/bill_classify/" + type + "_bill_classify",
            dataType: "json",
            type: "post",
            async: false,
            data: $addClassifyModal.find("form").serialize(),
            success: function (data) {
                alert("保存成功！！！");
                $addClassifyModal.modal("hide");
                loadClassify();
            },
            error: function () {

            }
        });
    }

    //注销分类的函数
    function deleteClassify() {
        var $classifyModal = $("#delete-modal");
        var $ulThird = $examineClassify.find("ul.nav-third[menu-expanded=true]");
        var $submit = $classifyModal.find(".modal-footer").find("button:first");
        $submit.off("click");
        var $a = $examineClassify.find("a.menuFocus");
        if ($ulThird.length > 0) {
            var dataId = $a.length > 0 ? $a.attr("data-id") : $ulThird.siblings("a").attr("data-id");
            submitForm(dataId);
            log4j.info(dataId);
        } else {
            var dataId = $a.attr("data-id");
            submitForm(dataId);
        }

        function submitForm(dataId) {
            $classifyModal.modal("show");
            $submit.on("click", function () {
                $.ajax({
                    url: hostUrl + "/cli/bill_classify/delete_by_primary_key?id=" + dataId,
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (data) {
                        log4j.info(data);
                        $classifyModal.modal("hide");
                        loadClassify();
                    },
                    error: function () {

                    }
                });
            });
        }
    }

    //新增开单套餐的函数
    function addInfo() {
        var $addClassifyModal = $("#add-info-modal");
        var $submit = $addClassifyModal.find(".modal-footer").find("button:first");
        $submit.off("click");
        var dataId = $examineSetMeal.find("tbody").attr("data-id");
        submitForm(dataId);

        function submitForm(dataId) {
            $addClassifyModal.modal("show");
            $addClassifyModal.find("input[type=text]").val("");
            $addClassifyModal.find("input[type=checkbox]").prop("checked", false);
            $addClassifyModal.find("input[name=id]").val(dataId);
            $submit.on("click", function () {
                saveInfo($addClassifyModal, "create");
            });
        }
    }

    //编辑开单套餐的函数
    function editInfo() {
        var $classifyModal = $("#add-info-modal");
        var $submit = $classifyModal.find(".modal-footer").find("button:first");
        var $IDInput = $classifyModal.find("input[name=id]");
        var dataId = $examineSetMeal.find("tBody").find("tr.selected").attr("data-id");
        $submit.off("click");
        submitForm(dataId);

        function submitForm(dataId) {
            $classifyModal.modal("show");
            $.ajax({
                url: hostUrl + "/cli/bill_info/select_by_primary_key?id=" + dataId,
                dataType: "json",
                type: "post",
                async: false,
                success: function (data) {
                    var $texts = $classifyModal.find("input[type=text]");
                    textVal($texts, data.data);
                    var $checkboxs = $classifyModal.find("input[type=checkbox]");
                    checkboxVal($checkboxs, data.data);
                    var $selects = $classifyModal.find("select");
                    textVal($selects, data.data);
                    $submit.on("click", function () {
                        $IDInput.val(dataId);
                        saveInfo($classifyModal, "update");
                    });
                },
                error: function () {

                }
            });
        }
    }

    //开单套餐保存的函数
    function saveInfo($addClassifyModal, type) {
        $.ajax({
            url: hostUrl + "/cli/bill_info/" + type + "_bill_info",
            dataType: "json",
            type: "post",
            async: false,
            data: $addClassifyModal.find("form").serialize(),
            success: function (data) {
                alert("保存成功！！！");
                $addClassifyModal.modal("hide");
                setMealChange($examineSetMeal, $examineClassify.find("a.menuItem.menuFocus"));
            },
            error: function () {

            }
        });
    }

    //开单套餐保存的函数
    function deleteInfo() {
        var $deleteModal = $("#delete-modal");
        var $submit = $deleteModal.find(".modal-footer").find("button:first");
        var dataId = $examineSetMeal.find("tr.selected").attr("data-id");
        $submit.off("click");
        submitForm(dataId);

        function submitForm(dataId) {
            $deleteModal.modal("show");
            $submit.on("click", function () {
                $.ajax({
                    url: hostUrl + "/cli/bill_info/delete_by_primary_key?id=" + dataId,
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (data) {
                        log4j.info(data);
                        $deleteModal.modal("hide");
                        setMealChange($examineSetMeal, $examineClassify.find("a.menuItem.menuFocus"));
                    },
                    error: function () {

                    }
                });
            });
        }
    }

}($("#pacs")));
